<template>
  <div v-if="loading" class="profile-loading">
    <el-skeleton :rows="10" animated />
  </div>
  <div v-else-if="!user" class="profile-not-login">
    <el-empty description="请先登录" />
    <el-button type="primary" class="login-btn" @click="redirectToLogin">去登录</el-button>
  </div>
  <div v-else class="profile-page">
    <div class="profile-container">
      <el-card class="profile-header" :body-style="{ padding: 0 }">
        <div class="profile-header-main">
          <div class="profile-avatar-wrapper">
            <img :src="user?.avatar || defaultAvatar" class="profile-avatar" />
          </div>
          <div class="profile-header-info">
            <div class="profile-username">{{ user?.username || '未设置用户名' }}</div>
            <div class="profile-email">{{ user?.email || '未绑定邮箱' }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="profile-content">
        <el-tabs v-model="activeTab" class="profile-tabs" type="border-card" @tab-change="handleTabChange">
          <el-tab-pane label="用户信息管理" name="info">
            <user-info-management 
              :user="user" 
              @update:user="updateUser"
            />
          </el-tab-pane>

          <el-tab-pane label="订单管理" name="orders">
            <order-management />
          </el-tab-pane>

          <!-- <el-tab-pane label="支付管理" name="payment">
            <payment-management />
          </el-tab-pane> -->

          <el-tab-pane label="消息中心" name="messages">
            <message-center />
          </el-tab-pane>

          <el-tab-pane label="账号管理" name="account">
            <el-card class="account-card" shadow="never">
              <div class="account-section">
                <h3 class="section-title">修改密码</h3>
                <el-form label-width="110px" class="profile-form" @submit.prevent>
                  <el-form-item label="原密码">
                    <el-input v-model="changePwdForm.oldPwd" type="password" />
                  </el-form-item>
                  <el-form-item label="新密码">
                    <el-input v-model="changePwdForm.newPwd" type="password" />
                  </el-form-item>
                  <el-form-item label="确认新密码">
                    <el-input v-model="changePwdForm.confirmPwd" type="password" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleChangePwd">修改密码</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <el-divider />
              
              <div class="account-section">
                <h3 class="section-title">账号安全</h3>
                <div class="logout-section">
                  <p class="logout-warning">退出登录后，将需要重新输入用户名和密码</p>
                  <el-button type="danger" @click="handleLogout">退出账号</el-button>
                </div>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { apiGetUserInfo } from '@/api/api'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import UserInfoManagement from '@/components/profile/UserInfoManagement.vue'
import OrderManagement from '@/components/profile/OrderManagement.vue'
import PaymentManagement from '@/components/profile/PaymentManagement.vue'
import MessageCenter from '@/components/profile/MessageCenter.vue'

const user = ref<any>(null)
const defaultAvatar = 'https://cdn-icons-png.flaticon.com/512/149/149071.png'
const activeTab = ref('info')
const loading = ref(true)

const router = useRouter()
const route = useRoute()
const changePwdForm = ref({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})

function updateUser(newUserInfo: any) {
  user.value = newUserInfo
}

function handleChangePwd() {
  if (!changePwdForm.value.oldPwd || !changePwdForm.value.newPwd || !changePwdForm.value.confirmPwd) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (changePwdForm.value.newPwd !== changePwdForm.value.confirmPwd) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  // 这里调用后端修改密码接口
  ElMessage.success('密码修改成功（示例）')
  changePwdForm.value.oldPwd = ''
  changePwdForm.value.newPwd = ''
  changePwdForm.value.confirmPwd = ''
}

function handleLogout() {
  localStorage.removeItem('token')
  user.value = null
  ElMessage.success('已退出登录')
  router.push('/login')
}

function redirectToLogin() {
  const redirectPath = `/profile${route.query.tab ? `?tab=${route.query.tab}` : ''}`
  router.push(`/login?redirect=${encodeURIComponent(redirectPath)}`)
}

function handleTabChange(tabName: string) {
  router.replace({ query: { ...route.query, tab: tabName } })
}

onMounted(async () => {
  loading.value = true
  
  // 从URL参数获取tab值
  const tabParam = route.query.tab as string
  if (tabParam && ['info', 'orders', 'payment', 'messages', 'account'].includes(tabParam)) {
    activeTab.value = tabParam
  }
  
  try {
    const res = await apiGetUserInfo()
    if (res.code === 200) {
      user.value = res.data
    } else {
      user.value = null
    }
  } catch (e) {
    user.value = null
  }
  loading.value = false
})
</script>

<style scoped>
.profile-page {
  min-height: 90vh;
  background: #f5f7fa;
  padding: 40px 16px;
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-loading {
  max-width: 1200px;
  margin: 60px auto;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.profile-not-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
}

.login-btn {
  margin-top: 24px;
}

.profile-header {
  margin-bottom: 24px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.profile-header:hover {
  transform: translateY(-5px);
}

.profile-header-main {
  display: flex;
  align-items: center;
  padding: 32px;
  background: linear-gradient(135deg, #1976d2 0%, #64b5f6 100%);
}

.profile-avatar-wrapper {
  position: relative;
  margin-right: 32px;
}

.profile-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #ffffff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

.profile-header-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.profile-username {
  font-size: 2.2rem;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.profile-email {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.9);
}

.profile-content {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.profile-tabs {
  background: transparent;
}

.profile-form {
  max-width: 500px;
}

.account-card {
  border: none;
  box-shadow: none !important;
}

.account-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: 600;
}

.logout-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.logout-warning {
  color: #909399;
  margin-bottom: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-header-main {
    flex-direction: column;
    text-align: center;
    padding: 24px;
  }
  
  .profile-avatar-wrapper {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .profile-header-info {
    align-items: center;
  }
  
  .profile-form {
    width: 100%;
  }
}
</style> 